var last_client_x = 0;
var last_client_y = 0;

function min(a, b) {
    return a < b ? a : b;
}
function max(a, b) {
    return a > b ? a : b;
}

// 触屏兼容
function touchEventToMouseEvent(event, eventType) {
    if (event == undefined) {
        return null;
    }
    var te = event.touches[0];
    if (te == undefined) {
    } else {
        var clientX = te.clientX, clientY = te.clientY, screenX = te.screenX, screenY = te.screenY;
        last_client_x = clientX;
        last_client_y = clientY;
    }

    return {
        clientX: last_client_x,
        clientY: last_client_y,
        screenX: screenX,
        screenY: screenY,
        button: 0,
        buttons: 0,
        stopPropagation: function () { event.stopPropagation() }
    };
}
function bind_mouse_start(obj, func) {
    obj.addEventListener('touchstart', function (e) {
        var simEvent = touchEventToMouseEvent(e, 'mousedown');
        if (simEvent != null) {
            func(simEvent);
        }
    });
    obj.onmousedown = func
}
function bind_mouse_move(obj, func) {
    document.ontouchmove = function (e) {
        var simEvent = touchEventToMouseEvent(e, 'mousemove');
        if (simEvent != null) {
            func(simEvent);
        }
    };
    document.getElementById("win_movecover").onmousemove = func
    document.onmousemove = func
}

function bind_mouse_end(obj, func) {
    document.ontouchend = function (e) {
        var simEvent = touchEventToMouseEvent(e, 'mouseup');
        if (simEvent != null) {
            func(simEvent);
        }
    };
    document.getElementById("win_movecover").onmouseup = func
    document.onmouseup = func
}

var win_wininfo = {}; // 窗口索引
var win_winid = 0; // 窗口编号
var win_iconid = 0; // 桌面图标编号
const win_ZINDEXBASE = 100; // zindex初始值
var win_zindexid = 0; // zindex编号
var win_desktop_showing = 0; // 当前是否显示桌面
var win_icon_last_choose = 0; // 最后选择的图标
var last_win_id = -1; // 最后选择的窗口
var win_windata = {}; // 窗口保存的数据
function ignore() { // 空回调

}
function win_create_window(w = 400, h = 200, title = "Window", context = "") {
    console.log("==> Create window")
    if (win_desktop_showing == 1) {
        win_show_desktop(); // 取消显示桌面
    }
    var template = `
                    <div class="win_window" id="win_window-id--{-{winid}-}-">
                        <div class="win_window-title">
                            <div class="win_window-button">
                                <div class="win_window-button-red" id="win_window-button-red-id--{-{winid}-}-"></div>
                                <div class="win_window-button-yellow" id="win_window-button-yellow-id--{-{winid}-}-"></div>
                                <div class="win_window-button-green" id="win_window-button-green-id--{-{winid}-}-"></div>
                            </div>
                            <span id="win_window-title-id--{-{winid}-}-">-{-{title}-}-</span>
                        </div>
                        <div class="win_window-context" id="win_window-context-id--{-{winid}-}-">-{-{context}-}-</div>
                        <div class="win_window-size" id="win_window-size-id--{-{winid}-}-">
                    </div>` // 模板
    var template_header = `
                    <div class="win_header-button" id="win_header-button-id--{-{winid}-}-">
                        <p id="win_header-button-text-id--{-{winid}-}-">-{-{title}-}-</p>
                        <div class="win_header-button-highlight" id="win_header-button-highlight-id--{-{winid}-}-"></div>
                    </div>`
    w = min(w, window.innerWidth)
    h = min(h, window.innerHeight - 32)
    win_wininfo[++win_winid] = {
        "title": title,
        "x": max(0, min(10, window.innerWidth - w)),
        "y": max(0, min(10, window.innerHeight - h)),
        "width": w,
        "height": h,
        "onclose": (ignore), // return 1 to ignore
        "minwidth": min(200, window.innerWidth),
        "minheight": min(24, window.innerHeight),
        "mode": 0, // 0:normal 1:min 2:max
        "side": 0, // 1:left 2:right
        "functions": {
            "min": (ignore),
            "max": (ignore),
            "normal": (ignore),
            "close": (ignore),
            "moveto": (ignore)
        }
    }
    win_windata[win_winid] = null;
    var ftemplate = template.replace(/-{-{winid}-}-/g, (win_winid).toString()).replace(/-{-{title}-}-/g, title).replace(/-{-{context}-}-/g, context) // 渲染模板
    var ftemplateh = template_header.replace(/-{-{winid}-}-/g, (win_winid).toString()).replace(/-{-{title}-}-/g, title).replace(/-{-{context}-}-/g, context)
    document.getElementById("win_container").insertAdjacentHTML("beforeend", ftemplate); // 插入
    document.getElementById("win_header").insertAdjacentHTML("beforeend", ftemplateh); // 插入标签
    setTimeout(() => {
        (function (winid_now) {
            var now_iframe = document.getElementById("win_window-id-" + winid_now.toString()).getElementsByTagName("iframe")[0];
            if (now_iframe != undefined) {
                now_iframe.contentWindow.neutron_winid = winid_now;
            }

            // 设置基本属性
            document.getElementById("win_window-id-" + winid_now.toString()).style.width = win_wininfo[winid_now].width + "px";
            document.getElementById("win_window-id-" + winid_now.toString()).style.height = win_wininfo[winid_now].height + "px";
            document.getElementById("win_window-id-" + winid_now.toString()).style.left = win_wininfo[winid_now].x + "px";
            document.getElementById("win_window-id-" + winid_now.toString()).style.top = win_wininfo[winid_now].y + "px";
            document.getElementById("win_window-id-" + winid_now.toString()).style.zIndex = win_ZINDEXBASE + (win_zindexid++)
            last_win_id = winid_now;
            document.getElementById("win_window-id-" + winid_now.toString()).style.display = "block";


            // 关闭函数
            win_wininfo[winid_now].functions.close = function (doonclose = true) {
                if (win_desktop_showing == 1) {
                    win_show_desktop(); // 取消显示桌面
                }
                if (doonclose != false) { // 判断是否执行回调
                    var ret = win_wininfo[winid_now].onclose(winid_now); // 执行关闭前函数
                } else {
                    var ret = 0;
                }
                if (ret != 1) { // 如果返回值不为1，则关闭窗口
                    last_win_id = -1
                    delete win_wininfo[winid_now]; // 删除窗口信息
                    delete win_windata[win_winid]; // 删除窗口数据
                    document.getElementById("win_window-id-" + winid_now.toString()).outerHTML = ""; // 删除元素
                    document.getElementById("win_header-button-id-" + winid_now.toString()).style.width = "0"; // 隐藏菜单栏
                    setTimeout(() => {
                        document.getElementById("win_header-button-id-" + winid_now.toString()).outerHTML = ""; // 删除元素
                    }, 300)
                }
                return false;
            }
            // 最大化
            win_wininfo[winid_now].functions.max = function (side = 0) {
                if (side != 0 && side != 1 && side != 2) {
                    side = 0
                }
                if (win_desktop_showing == 1) {
                    win_show_desktop(); // 取消显示桌面
                }
                if (win_wininfo[winid_now].mode == 1) { // 如果当前已经最大化
                    win_wininfo[winid_now].functions.normal()
                    win_wininfo[winid_now].side = 0
                } else {
                    win_wininfo[winid_now].side = side
                    win_wininfo[winid_now].mode = 1
                    if (side == 0) {
                        // 设置窗口属性
                        document.getElementById("win_window-id-" + winid_now.toString()).style.width = "calc(100% - 8px)"; // 全屏
                        document.getElementById("win_window-id-" + winid_now.toString()).style.height = "calc(100% - 8px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.left = "4px";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.top = "4px";
                    } else if (side == 1) {
                        // 左贴靠
                        win_wininfo[winid_now].mode = 1
                        win_wininfo[winid_now].side = 1
                        document.getElementById("win_window-id-" + winid_now.toString()).style.width = "calc(50% - 6px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.height = "calc(100% - 8px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.left = "4px";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.top = "4px";
                    } else if (side == 2) {
                        // 右贴靠
                        document.getElementById("win_window-id-" + winid_now.toString()).style.width = "calc(50% - 6px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.height = "calc(100% - 8px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.left = "calc(50% + 2px)";
                        document.getElementById("win_window-id-" + winid_now.toString()).style.top = "4px";
                    }
                }
                return false; // 清除默认事件
            }
            // 最小化
            win_wininfo[winid_now].functions.min = function () {
                win_wininfo[winid_now].side = 0
                if (win_desktop_showing == 1) {
                    win_show_desktop(); // 取消显示桌面
                }
                if (win_wininfo[winid_now].mode == 2) { // 如果当前已经最小化
                    win_wininfo[winid_now].functions.normal()
                } else {
                    win_wininfo[winid_now].mode = 2
                    // 隐藏窗口
                    document.getElementById("win_window-id-" + winid_now.toString()).style.display = "none";
                }
                return false; // 清除默认事件
            }
            // 恢复
            win_wininfo[winid_now].functions.normal = function () {
                if (win_desktop_showing == 1) {
                    win_show_desktop(); // 取消显示桌面
                }
                document.getElementById("win_window-id-" + winid_now.toString()).style.zIndex = win_ZINDEXBASE + (win_zindexid++) // 置顶
                last_win_id = winid_now;

                win_wininfo[winid_now].mode = 0
                // 设置窗口属性
                document.getElementById("win_window-id-" + winid_now.toString()).style.width = win_wininfo[winid_now].width + "px";
                document.getElementById("win_window-id-" + winid_now.toString()).style.height = win_wininfo[winid_now].height + "px";
                document.getElementById("win_window-id-" + winid_now.toString()).style.left = win_wininfo[winid_now].x + "px";
                document.getElementById("win_window-id-" + winid_now.toString()).style.top = win_wininfo[winid_now].y + "px";
                document.getElementById("win_window-id-" + winid_now.toString()).style.display = "block";
                return false;
            }
            // 移动窗口
            win_wininfo[winid_now].functions.moveto = function (newX, newY) {
                document.getElementById("win_window-id-" + winid_now.toString()).style.transition = "none";
                setTimeout(() => {
                    win_wininfo[winid_now].x = newX;
                    win_wininfo[winid_now].y = newY;
                    document.getElementById("win_window-id-" + winid_now.toString()).style.left = newX + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.top = newY + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.width = win_wininfo[winid_now].width + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.height = win_wininfo[winid_now].height + "px";
                    setTimeout(() => {
                        document.getElementById("win_window-id-" + winid_now.toString()).style.transition = null;
                    }, 300)
                }, 0)
            }
            // 置顶
            win_wininfo[winid_now].functions.front = function () {
                document.getElementById("win_window-id-" + winid_now.toString()).style.zIndex = win_ZINDEXBASE + (win_zindexid++) // 置顶
                last_win_id = winid_now;
            }

            // 绑定按钮
            document.getElementById("win_window-button-red-id-" + winid_now.toString()).addEventListener("click", win_wininfo[winid_now].functions.close);
            document.getElementById("win_window-button-yellow-id-" + winid_now.toString()).addEventListener("click", win_wininfo[winid_now].functions.min);
            document.getElementById("win_window-button-green-id-" + winid_now.toString()).addEventListener("click", win_wininfo[winid_now].functions.max);

            document.getElementById("win_window-title-id-" + winid_now.toString()).addEventListener("contextmenu", function (e) {
                e.preventDefault()
                e.stopPropagation()
                windowShowContextMenu(winid_now)
            })
            document.getElementById("win_header-button-id-" + winid_now.toString()).addEventListener("contextmenu", function (e) {
                e.preventDefault()
                e.stopPropagation()
                windowShowContextMenu(winid_now)
            })

            bind_mouse_start(document.getElementById("win_window-title-id-" + winid_now.toString()), function (e) {
                if (e.button != 0) {
                    return
                }
                document.getElementById("win_movecover").style.display = "block"; // 拖动遮罩层
                document.getElementById("win_window-id-" + winid_now.toString()).style.zIndex = win_ZINDEXBASE + (win_zindexid++) // 置顶
                last_win_id = winid_now;

                document.getElementById("win_movecover").style.cursor = "move";

                if (win_wininfo[winid_now].mode != 0) { // 确保最大化等模式下拖拽还原
                    win_wininfo[winid_now].mode = 0;

                    // 重置宽高位置
                    document.getElementById("win_window-id-" + winid_now.toString()).style.width = win_wininfo[winid_now].width + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.height = win_wininfo[winid_now].height + "px";
                    win_wininfo[winid_now].x = e.clientX - Math.floor(e.clientX / document.getElementById("win_container").clientWidth * win_wininfo[winid_now].width);
                    win_wininfo[winid_now].y = 0;
                    document.getElementById("win_window-id-" + winid_now.toString()).style.left = win_wininfo[winid_now].x + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.top = win_wininfo[winid_now].y + "px";
                }

                // 设置拖拽起点
                var x = e.clientX - win_wininfo[winid_now].x;
                var y = e.clientY - win_wininfo[winid_now].y;
                // 关闭动画
                document.getElementById("win_window-id-" + winid_now.toString()).style.transition = "none";

                bind_mouse_move(document.getElementById("win_window-size-id-" + winid_now.toString()), function (e) { // 绑定拖拽
                    // 计算新位置
                    var newX = e.clientX - x;
                    var newY = e.clientY - y;

                    // 边界
                    if (newX < 0) newX = 0;
                    if (newY < 0) newY = 0;
                    if (newX > document.getElementById("win_container").clientWidth - win_wininfo[winid_now].width) newX = document.getElementById("win_container").clientWidth - win_wininfo[winid_now].width;
                    if (newY > document.getElementById("win_container").clientHeight - win_wininfo[winid_now].height) newY = document.getElementById("win_container").clientHeight - win_wininfo[winid_now].height;

                    // 更新位置
                    win_wininfo[winid_now].x = newX;
                    win_wininfo[winid_now].y = newY;
                    document.getElementById("win_window-id-" + winid_now.toString()).style.left = newX + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.top = newY + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.width = win_wininfo[winid_now].width + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.height = win_wininfo[winid_now].height + "px";

                    // 停止事件冒泡
                    e.stopPropagation();
                })

                bind_mouse_end(document.getElementById("win_window-size-id-" + winid_now.toString()), function (e) { // 结束拖动
                    if (e.clientY - 25 <= 3) { // 顶部最大化
                        win_wininfo[winid_now].functions.max()
                    } else if (e.clientX >= document.getElementById("win_container").clientWidth - 3) { // 右侧贴靠
                        win_wininfo[winid_now].functions.max(2)
                    } else if (e.clientX <= 3) { // 左侧贴靠
                        win_wininfo[winid_now].functions.max(1)
                    }
                    // 取消事件
                    document.onmousemove = null;
                    document.onmouseup = null;
                    document.ontouchmove = null;
                    document.ontouchend = null;
                    document.getElementById("win_movecover").style.display = "none"; // 拖动遮罩层

                    document.getElementById("win_movecover").style.cursor = "default";

                    // 恢复动画
                    document.getElementById("win_window-id-" + winid_now.toString()).style.transition = "all 0.1s ease-in-out 0.1s";
                })
            });

            // 拖动缩放事件
            bind_mouse_start(document.getElementById("win_window-size-id-" + winid_now.toString()), function (e) {
                if (e.button != 0) {
                    return
                }
                document.getElementById("win_movecover").style.display = "block"; // 拖动遮罩层
                document.getElementById("win_window-id-" + winid_now.toString()).style.zIndex = win_ZINDEXBASE + (win_zindexid++) // 置顶
                last_win_id = winid_now;

                // 最大化时忽略缩放
                if (win_wininfo[winid_now].mode != 0) {
                    return
                }

                // 禁用动画
                document.getElementById("win_window-id-" + winid_now.toString()).style.transition = "none";

                // 鼠标指针
                document.getElementById("win_movecover").style.cursor = "se-resize";

                // 开始拖动
                bind_mouse_move(document.getElementById("win_window-size-id-" + winid_now.toString()), function (e) {
                    // 新宽高
                    var newW = e.clientX - win_wininfo[winid_now].x;
                    var newH = e.clientY - win_wininfo[winid_now].y - 32;

                    // 边界
                    if (newW < win_wininfo[winid_now].minwidth) {
                        newW = win_wininfo[winid_now].minwidth;
                    }
                    if (newH < win_wininfo[winid_now].minheight) {
                        newH = win_wininfo[winid_now].minheight;
                    }
                    if (newW + win_wininfo[winid_now].x > document.getElementById("win_container").clientWidth) {
                        newW = document.getElementById("win_container").clientWidth - win_wininfo[winid_now].x;
                    }
                    if (newH + win_wininfo[winid_now].y > document.getElementById("win_container").clientHeight) {
                        newH = document.getElementById("win_container").clientHeight - win_wininfo[winid_now].y;
                    }

                    // 设置宽高
                    win_wininfo[winid_now].width = newW;
                    win_wininfo[winid_now].height = newH;
                    document.getElementById("win_window-id-" + winid_now.toString()).style.width = newW + "px";
                    document.getElementById("win_window-id-" + winid_now.toString()).style.height = newH + "px";

                })

                // 结束拖拽
                bind_mouse_end(document.getElementById("win_window-size-id-" + winid_now.toString()), function (e) {
                    e.preventDefault()
                    document.onmousemove = null;
                    document.onmouseup = null;
                    document.ontouchmove = null;
                    document.ontouchend = null;
                    document.getElementById("win_window-id-" + winid_now.toString()).style.transition = "all 0.1s ease-in-out 0.1s";
                    document.getElementById("win_movecover").style.display = "none"; // 拖动遮罩层
                    document.getElementById("win_movecover").style.cursor = "default";
                })
            })

            // 绑定标签栏按钮
            document.getElementById("win_header-button-id-" + winid_now.toString()).addEventListener('click', function () {
                if (last_win_id != winid_now) {
                    win_wininfo[winid_now].functions.front();
                } else {
                    win_wininfo[winid_now].functions.min();
                }
            })
        })(win_winid)
    }, 0)
    return win_winid
}
function win_show_desktop() { // 显示桌面
    if (win_desktop_showing == 0) { // 显示桌面
        // 动画
        document.getElementById("win_header-desktop-highlight").style.width = "calc(100% - 12px)";
        document.getElementById("win_header-desktop-highlight").style.height = "3px";
        document.getElementById("win_header-desktop-highlight").style.left = "6px";

        // 隐藏所有窗口
        for (var key in win_wininfo) {
            document.getElementById("win_window-id-" + key.toString()).style.display = "none";
        }
        win_desktop_showing = 1
    } else { // 取消显示
        // 动画
        document.getElementById("win_header-desktop-highlight").style.width = null;
        document.getElementById("win_header-desktop-highlight").style.height = null;
        document.getElementById("win_header-desktop-highlight").style.left = null;

        // 显示窗口
        for (var key in win_wininfo) {
            if (win_wininfo[key].mode != 2) {
                document.getElementById("win_window-id-" + key.toString()).style.display = "block";
            }
        }
        win_desktop_showing = 0
    }
    return false
}
function win_create_icon(name = "test", image = "https://cdn-icons-png.flaticon.com/512/5968/5968292.png", action = function () { win_create_window() }) { // 创建桌面图标
    var template = `
        <div class="win_icon" draggable="false" id="win_icon-id--{-{iconid}-}-">
            <div class="win_icon-image" draggable="false" id="win_icon-image-id--{-{iconid}-}-">
                <img src="-{-{image}-}-" draggable="false" width=64 height=64>
                </div>
            <span class="win_icon-title" id="win_icon-title-id--{-{iconid}-}-">-{-{name}-}-</span>
        </div>`
    var ftemplate = template.replace(/-{-{iconid}-}-/g, (++win_iconid).toString()).replace(/-{-{name}-}-/g, name).replace(/-{-{image}-}-/g, image) // 渲染模板
    document.getElementById("win_icon-container").insertAdjacentHTML("beforeend", ftemplate); // 插入元素

    (function (iconid_now, action_now) { // 环境隔离
        setTimeout(() => {
            document.getElementById("win_icon-id-" + (iconid_now).toString()).addEventListener('click', function (event) {
                if (win_icon_last_choose == iconid_now) { // 双击
                    action_now(iconid_now);
                    document.getElementById("win_icon-id-" + win_icon_last_choose.toString()).classList.remove("win_icon_active");
                    win_icon_last_choose = 0 // 取消选中
                } else { // 单击
                    if (win_icon_last_choose != 0) { // 取消原来图标的选中状态
                        document.getElementById("win_icon-id-" + win_icon_last_choose.toString()).classList.remove("win_icon_active");
                    }
                    document.getElementById("win_icon-id-" + iconid_now.toString()).classList.add("win_icon_active"); // 选择当前图标
                    win_icon_last_choose = iconid_now; // 设置当前图标选中
                }

                // 停止事件冒泡
                event.stopPropagation();
                return false;
            })
        }, 0)
    })(win_iconid, action)
}

function win_init() {
    document.getElementById("win_header").addEventListener('wheel', function (event) { // 菜单滚动
        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
        this.scrollLeft -= (delta * 40); // 每次滚动40个像素，可以根据需要进行调整
        return false;
    }, { passive: true });

    document.getElementById("win_container").addEventListener('click', function () { // 取消选择
        if (win_icon_last_choose != 0) { // 取消原来图标的选中状态
            document.getElementById("win_icon-id-" + win_icon_last_choose.toString()).classList.remove("win_icon_active");
            win_icon_last_choose = 0;
        }
    });

    document.getElementById("win_header-desktop").addEventListener('click', win_show_desktop) // 显示桌面
}

function windowShowContextMenu(winid) { // 窗口右键菜单
    menu_callback = function (ret) {
        if (ret == 0) {
            win_wininfo[winid].functions.close()
        } else if (ret == 1) {
            win_wininfo[winid].functions.max()
        } else if (ret == 2) {
            win_wininfo[winid].functions.min()
        } else if (ret == 3) {
            win_wininfo[winid].functions.normal()
        } else if (ret == 4) {
            alert("弹出功能是实验性功能，所有会话信息保存在本地（并且可能无法还原），并且插件可能会无法正常工作！")
            var link_obj = document.getElementById("win_window-context-id-" + winid.toString()).getElementsByTagName("iframe")[0];
            if (link_obj == undefined) {
                window.open("about:blank", win_wininfo[winid].title, "location=no,width=" + win_wininfo[winid].width + ",height=" + win_wininfo[winid].height + ",left=" + win_wininfo[winid].x + ",top=" + win_wininfo[winid].y).document.write(document.getElementById("win_window-context-id-" + winid.toString()).innerHTML)
            } else {
                link = link_obj.contentWindow.location.href
                window.open(link, win_wininfo[winid].title, "location=no,width=" + win_wininfo[winid].width + ",height=" + win_wininfo[winid].height + ",left=" + win_wininfo[winid].x + ",top=" + win_wininfo[winid].y)
            }
            win_wininfo[winid].functions.close()
        }
    }
    create_menu_on_mouse(["关闭", "最大化", "最小化", "还原", "弹出(实验)"])
}
function spaceShowContextMenu(event) {
    event.stopPropagation()
    event.preventDefault()
    menu_callback = function (ret) {
        if (ret == 0) {
            location.reload();
        }
    }
    create_menu_on_mouse(["刷新"])
}

CHECK_DESKTOP = 1